import router from '@/router'
import { RequestMenu } from '@/api/index'
const viteComponent = import.meta.glob('@/views/**/*.vue')
const menu = {
	namespaced: true,
	state: {
		menuList: [],
	},
	mutations: {
		SAVE_MENU(state, list) {
			state.menuList = list
		},
	},
	actions: {
		saveMenu({ commit }, roleId) {
			return new Promise(async (resolve, reject) => {
				// 2.1 获取动态菜单
				let data = await RequestMenu(roleId)
				let list = data.sysmenu
				// 1. 保存菜单数据
				commit('SAVE_MENU', list)
				// 2.格式化映射菜单数据为路由数据
				let menuRouesList = formateMenuList(list)
				// 3.添加动态路由
				menuRouesList.forEach(route => router.addRoute(route))
				
				resolve()
			})
		},
	},
	getters: {
		menuList: state => state.menuList,
	},
}

/**
 * 添加动态路由
 *  路由菜单接口数据映射成路由格式数据
 */
function formateMenuList(menuRoutes) {
	let newMenuRoutes = []
	menuRoutes.forEach(route => {
		// 如果有子路由，递归调用函数本身，继续映射
		let children
		if (route.children && route.children instanceof Array) {
			children = formateMenuList(route.children)
		}
		const { path, label, meta, iconCls, hidden } = route
		let newRoute = {
			path,
			label,
			meta,
			iconCls,
			hidden,
			children,
		}
		// 组件映射
		if (route.path.indexOf('/main') !== -1) {
			newRoute = {
				...newRoute,
				component: () => import('@/views/Home.vue'),
			}
		} else {
			newRoute = {
				...newRoute,
				// component: () => Promise.resolve(require(`@/views/platform${route.path}`).default), //webpack router4版本
				component: viteComponent[`/src/views/platform${route.path}.vue`], // vite router4
			}
		}

		newMenuRoutes.push(newRoute)
	})
	return newMenuRoutes
}

export default menu
